import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:gzmall_app/common/setting_util.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/mine/select_regions.dart';
import 'package:gzmall_app/model/regions.dart';
import 'package:gzmall_app/model/shop_validate.dart';
import 'package:image_picker/image_picker.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/api.dart';

class OpenStorePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => OpenStorePageState();
}

class OpenStorePageState extends State<OpenStorePage> {
  String _storeName = "",
      _personName = "",
      _phone = "",
      _area = "",
      _address = "",
      _provinceId = "",
      _cityId = "",
      _districtId = "";

  ShopValidate _shopValidate;

  TextEditingController _pNameController = TextEditingController(),
      _sNameController = TextEditingController(),
      _addressController = TextEditingController(),
      _phoneController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _getValidateInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _createAppBar(),
      body: Column(children: <Widget>[
        Expanded(
          child: ListView(padding: const EdgeInsets.only(top: 0.0), children: <
              Widget>[
            Container(
              margin: const EdgeInsets.only(bottom: 1.0),
              color: Colors.white,
              child: Column(
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(top: 16.0, bottom: 12.0),
                    child: Image.asset(
                      "images/open_store_ic.png",
                      width: 40.0,
                      height: 40.0,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 36.0),
                    child: Text(
                      "店铺信息",
                      textAlign: TextAlign.center,
                      style:
                          TextStyle(fontSize: 16.0, color: ColorCommon.black1),
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 36.0),
                    margin: const EdgeInsets.only(top: 10.0, bottom: 30.0),
                    child: Text(
                      "请填写正确的店铺信息，即可享受${SettingUtil.appName}的开店疯赚服务",
                      textAlign: TextAlign.center,
                      style:
                          TextStyle(fontSize: 12.0, color: ColorCommon.black1),
                    ),
                  ),
                ],
              ),
            ),
            _createInputItem("店铺名称", false, "请填写您的店铺名称", (str) {
              _storeName = str ?? '';
            }, _sNameController),
            _createInputItem("联系人", false, "请填写您的姓名", (str) {
              _personName = str ?? "";
            }, _pNameController),
            GestureDetector(
              onTap: () {
                Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                  return SelectRegionsPage();
                })).then((value) {
                  if (value != null) {
                    Regions r1 = Regions.fromJson(value["1"]);
                    Regions r2 = Regions.fromJson(value["2"]);
                    Regions r3 = Regions.fromJson(value["3"]);
                    if (!mounted) return;
                    setState(() {
                      _provinceId = r1.id.toString();
                      _cityId = r2.id.toString();
                      _districtId = r3.id.toString();
                      _area = r1.value + r2.value + r3.value;
                    });
                  }
                });
              },
              child: Container(
                color: Colors.white,
                height: 50.0,
                padding: const EdgeInsets.symmetric(horizontal: 10.0),
                child: Row(children: <Widget>[
                  Container(
                    width: 70.0,
                    child: Text(
                      "地址",
                      style:
                          TextStyle(fontSize: 12.0, color: ColorCommon.black1),
                    ),
                  ),
                  Expanded(
                    child: Text(
                      _area ?? "请选择地址",
                      style:
                          TextStyle(fontSize: 12.0, color: ColorCommon.black1),
                    ),
                  ),
                  Image.asset("images/right_arrow.png",
                      width: 10.0, height: 10.0),
                ]),
              ),
            ),
            _createInputItem("门牌号", false, "例:16号楼427室", (str) {
              _address = str ?? '';
            }, _addressController),
            _createInputItem("固话号码", false, "请输入固定电话号码", (str) {
              _phone = str ?? '';
            }, _phoneController),
            Container(
              color: Colors.white,
              padding:
                  const EdgeInsets.symmetric(horizontal: 10.0, vertical: 15.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Container(
                    margin: const EdgeInsets.only(bottom: 10.0),
                    child: Text(
                      "请按图示要求上传您的相关证件照片",
                      textAlign: TextAlign.left,
                      style:
                          TextStyle(fontSize: 12.0, color: ColorCommon.grey3),
                    ),
                  ),
                  Wrap(
                    spacing: 10.0,
                    runSpacing: 10.0,
                    children: <Widget>[
                      _createImageSelect(2),
                      _createImageSelect(3),
                      _createImageSelect(1),
                      _createImageSelect(4),
                    ],
                  ),
                ],
              ),
            ),
          ]),
        ),
        InkWell(
          onTap: () {
            _validateStoreFile(_storeName, null, null, null, null, _personName,
                _phone, _provinceId, _cityId, _districtId, _address, true);
          },
          child: Container(
            alignment: Alignment.center,
            height: 50.0,
            color: ColorCommon.primaryColor,
            child: Text(
              "立即开店",
              style: TextStyle(fontSize: 16.0, color: Colors.white),
            ),
          ),
        ),
      ]),
    );
  }

  _createAppBar() {
    return new AppBar(
      elevation: 0.0,
      title: new Text("立即开店"),
      leading: new IconButton(
        icon: new Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: <Widget>[],
    );
  }

  _createInputItem(String tips, bool obscureText, String hint,
      Function onChanged, TextEditingController controller,
      {Widget child}) {
    return Container(
      height: 50.0,
      padding: const EdgeInsets.only(left: 10.0, right: 10.0),
      margin: const EdgeInsets.only(bottom: 1.0),
      alignment: Alignment.center,
      decoration: BoxDecoration(color: Colors.white),
      child: Row(
        children: <Widget>[
          Container(
            width: 70.0,
            child: Text(
              tips,
              style: TextStyle(fontSize: 12.0, color: ColorCommon.black1),
            ),
          ),
          Expanded(
            child: TextField(
              obscureText: obscureText,
              controller: controller,
              style: TextStyle(fontSize: 12.0, color: ColorCommon.black1),
              decoration: InputDecoration.collapsed(
                hintText: hint,
                hintStyle: TextStyle(fontSize: 12.0, color: ColorCommon.grey1),
              ),
              onChanged: onChanged,
            ),
          ),
          child ?? Container(),
        ],
      ),
    );
  }

  _createImageSelect(int type) {
    double _width = (MediaQuery.of(context).size.width - 30) / 2,
        _height = _width / 1.6;
    File _image;
    String _imageUrl;
    String _imageAsset;
    switch (type) {
      case 1:
        _image = _storeImage;
        _imageUrl = _shopValidate != null &&
                _shopValidate.avatar != null &&
                _shopValidate.avatar.isNotEmpty
            ? _shopValidate.avatar
            : "";
        _imageAsset = "images/open_store_3.png";
        break;
      case 2:
        _image = _idCard1Image;
        _imageUrl = _shopValidate != null &&
                _shopValidate.idcardFront != null &&
                _shopValidate.idcardFront.isNotEmpty
            ? _shopValidate.idcardFront
            : "";
        _imageAsset = "images/open_store_1.png";
        break;
      case 3:
        _image = _idCard2Image;
        _imageUrl = _shopValidate != null &&
                _shopValidate.idcardBack != null &&
                _shopValidate.idcardBack.isNotEmpty
            ? _shopValidate.idcardBack
            : "";
        _imageAsset = "images/open_store_2.png";
        break;
      case 4:
        _image = _licenseImage;
        _imageUrl = _shopValidate != null &&
                _shopValidate.license != null &&
                _shopValidate.license.isNotEmpty
            ? _shopValidate.license
            : "";
        _imageAsset = "images/open_store_4.png";
        break;
      default:
    }
    return InkWell(
        onTap: () {
          _currentType = type;
          _showSelectPhoto();
        },
        child: _image == null && (_imageUrl == null || _imageUrl.isEmpty)
            ? Image.asset(
                _imageAsset,
                width: _width,
                height: _height,
                fit: BoxFit.fill,
              )
            : (_image != null
                ? Image.file(
                    _image,
                    width: _width,
                    height: _height,
                    fit: BoxFit.fill,
                  )
                : CachedNetworkImage(
                    imageUrl: _imageUrl,
                    width: _width,
                    height: _height,
                    fit: BoxFit.fill,
                  )));
  }

  _showSelectPhoto() {
    showCupertinoModalPopup(
      context: context,
      builder: (_) {
        return CupertinoActionSheet(
          actions: <Widget>[
            CupertinoActionSheetAction(
              onPressed: () {
                _getImage(ImageSource.camera);
                Navigator.of(context).pop();
              },
              child: Text("拍照"),
            ),
            CupertinoActionSheetAction(
              onPressed: () {
                _getImage(ImageSource.gallery);
                Navigator.of(context).pop();
              },
              child: Text("相册"),
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            onPressed: () {
              Navigator.of(context).pop();
            },
            child: Text("取消"),
          ),
        );
      },
    );
  }

  int _currentType;
  File _storeImage, _idCard1Image, _idCard2Image, _licenseImage;

  Future _getImage(ImageSource source) async {
    var image = await ImagePicker.pickImage(source: source, maxWidth: 600.0);

    if (!mounted) return;
    setState(() {
      switch (_currentType) {
        case 1:
          _storeImage = image;
          _validateStoreFile(null, _storeImage, null, null, null, null, null,
              null, null, null, null, false);
          break;
        case 2:
          _idCard1Image = image;
          _validateStoreFile(null, null, _idCard1Image, null, null, null, null,
              null, null, null, null, false);
          break;
        case 3:
          _idCard2Image = image;
          _validateStoreFile(null, null, null, _idCard2Image, null, null, null,
              null, null, null, null, false);
          break;
        case 4:
          _licenseImage = image;
          _validateStoreFile(null, null, null, null, _licenseImage, null, null,
              null, null, null, null, false);
          break;
        default:
      }
    });
  }

  _validateStoreFile(
      String name,
      File avatar,
      File idcardFront,
      File idcardBack,
      File license,
      String contactName,
      String contactPhone,
      String provinceId,
      String cityId,
      String districtId,
      String address,
      bool isCheck) {
    if (isCheck) {
      // if (avatar == null) {
      //   ToastUtil.showToast("请上传店铺头像");
      //   return;
      // }
      if (name == null || name.isEmpty) {
        ToastUtil.showMessageToast("请输入店铺名称");
        return;
      }
      if (contactName == null || contactName.isEmpty) {
        ToastUtil.showMessageToast("请输入联系人");
        return;
      }
      if (_area == null || _area.isEmpty) {
        ToastUtil.showMessageToast("请选择地址");
        return;
      }
      if (address == null || address.isEmpty) {
        ToastUtil.showMessageToast("门牌号");
        return;
      }
      if (contactPhone == null || contactPhone.isEmpty) {
        ToastUtil.showMessageToast("请输入固定电话");
        return;
      }
      // if (idcardFront == null) {
      //   ToastUtil.showToast("请上传身份证正面照");
      //   return;
      // }
      // if (idcardBack == null) {
      //   ToastUtil.showToast("请上传身份证反面照");
      //   return;
      // }
      // if (license == null) {
      //   ToastUtil.showToast("请上传工商营业执照");
      //   return;
      // }
    }

    Map<String, dynamic> params = {};
    if (name != null && name.isNotEmpty) {
      params.addAll({"shop[name]": name});
    }
    if (avatar != null) {
      params.addAll({"shop[avatar]": MultipartFile.fromFileSync(avatar.path)});
    }
    if (idcardFront != null) {
      params.addAll(
          {"shop[idcard_front]": MultipartFile.fromFileSync(idcardFront.path)});
    }
    if (idcardBack != null) {
      params.addAll(
          {"shop[idcard_back]": MultipartFile.fromFileSync(idcardBack.path)});
    }
    if (license != null) {
      params
          .addAll({"shop[license]": MultipartFile.fromFileSync(license.path)});
    }
    if (contactName != null && contactName.isNotEmpty) {
      params.addAll({"shop[contact_name]": contactName});
    }
    if (contactPhone != null && contactPhone.isNotEmpty) {
      params.addAll({"shop[contact_phone]": contactPhone});
    }
    if (provinceId != null && provinceId.isNotEmpty) {
      params.addAll({"shop[province_id]": provinceId});
    }
    if (cityId != null && cityId.isNotEmpty) {
      params.addAll({"shop[city_id]": cityId});
    }
    if (districtId != null && districtId.isNotEmpty) {
      params.addAll({"shop[district_id]": districtId});
    }
    if (address != null && address.isNotEmpty) {
      params.addAll({"shop[address]": address});
    }
    FormData formData = new FormData.fromMap(params);
    NetUtil.post(context, Api.openShopsValidate, (data, message) {
      ToastUtil.showMessageToast(message);
      if (isCheck) {
        Navigator.of(context).pop();
      }
    }, params: formData, isShowLoading: true);
  }

  _getValidateInfo() {
    NetUtil.get(
      context,
      Api.openShopsValidateInfo,
      (data, message) {
        if (!mounted) return;
        setState(() {
          _shopValidate = ShopValidate.fromJson(data);
          if (_shopValidate != null) {
            _storeName = _shopValidate.name;
            _personName = _shopValidate.contactName;
            _phone = _shopValidate.contactPhone;
            _provinceId = _shopValidate.provinceId.toString();
            _cityId = _shopValidate.cityId.toString();
            _districtId = _shopValidate.districtId.toString();
            _address = _shopValidate.address;
            _area = _shopValidate.province +
                _shopValidate.city +
                _shopValidate.district;
          }
        });
      },
    );
  }
}
